import React from 'react';
import ReactDOM from 'react-dom';
import {Provider} from 'react-redux';
import store from './store';
import {countAdd, countJian} from './actions/countAction';
import {loadData} from './actions/dataAction';
import './index.css';
import App from './App';
import * as serviceWorker from './serviceWorker';


/**
 * Redux中三个重要部分：
 *  1.Action
 *  2.Reducer
 *  3.Store(state)
 **/
console.log(store);
store.dispatch(countAdd);
store.dispatch(countJian);
store.dispatch(loadData);


/**
// 创建一个 Reducer
const reducer = (state = {
    count: 1
}, action) => {
    // state = {
    //     name: '陈皮皮',
    //     age: 23
    // };
    switch (action.type) {
        case 'COUNT_ADD':
            return {
                ...state,
                count: ++state.count
            };
        case 'COUNT_JIAN':
            return {
                ...state,
                count: --state.count
            };
        default:
            return state;
    }
};
const reducer1 = (state = {
    list: [{
        title: '你好'
    }]
}, action) => {
    switch (action.type) {
        case 'LOAD_DATA':
            return {
                ...state,
                list: action.payload
            };
        default:
            return state;
    }
};


// 合并多个 reducer
const allReducers = combineReducers({
    counter: reducer,
    data: reducer1
});



// 创建一个Store
const store = createStore(
    allReducers,
    compose(
        applyMiddleware(...[thunk]),
        window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__()
    )
);
console.log(store);
console.log(store.getState());

// 改变reducer中的值， 需要通过 dispatch 去派发一个 action
store.dispatch({
    type: 'COUNT_ADD',
    payload: {}
});

console.log(store);
console.log(store.getState());


store.dispatch({
    type: 'COUNT_JIAN',
    payload: {}
});

console.log(store);
console.log(store.getState());


// 发送ajax请求，获取网络数据
const getData = () => {
    return get('http://jsonplaceholder.typicode.com/posts');
};

store.dispatch(async function(dispatch) {
    const res = await getData();
    console.log(res.data);
    dispatch({
        type: 'LOAD_DATA',
        payload: res.data
    });
});
*/



ReactDOM.render( 
    <Provider store={store}>
        <App />
    </Provider>, 
    document.getElementById('root')
);

// If you want your app to work offline and load faster, you can change
// unregister() to register() below. Note this comes with some pitfalls.
// Learn more about service workers: http://bit.ly/CRA-PWA
serviceWorker.unregister();